package com.example.baiguangsystem.service.impl;

import com.example.baiguangsystem.entity.LoginStatusEnum;
import com.example.baiguangsystem.entity.Paging;
import com.example.baiguangsystem.entity.User;
import com.example.baiguangsystem.mapper.UserMapper;
import com.example.baiguangsystem.service.UserService;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpResponse;
import java.util.Enumeration;
import java.util.List;

/**
 * 用户功能实现类
 *
 * @Author: 27641
 * @ProjectName: BaiGuangSystem
 * @Date: 2022/02/02/23:06
 * @noinspection SpellCheckingInspection
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * 依赖注入
     */
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录业务功能实现
     *
     * @param user    前端用户输入的登录信息封装
     * @param session 用于存储用户状态
     * @return 登录状态
     */
    @SneakyThrows
    @Override
    public LoginStatusEnum login(User user, HttpSession session, HttpServletResponse httpResponse) {
        User findUserResult = this.userMapper.login(user);
        /*如果登录成功就记录登录状态*/
        if (findUserResult != null) {
            boolean userNameEquals = findUserResult.getUserName().equals(user.getUserName());
            boolean userPasswordEquals = findUserResult.getUserPassword().equals(user.getUserPassword());
            if (userNameEquals && userPasswordEquals) {
                String key = URLEncoder.encode(user.getUserId() + user.getUserName() + user.getUserPassword(),
                        "UTF-8");
                String cookieValue = URLEncoder.encode(user.toString(), "UTF-8");
                session.setAttribute(key, user);
                Cookie cookie = new Cookie(key, cookieValue);
                cookie.setPath("/BaiGuang");
                cookie.setMaxAge(60 * 10);
                httpResponse.addCookie(cookie);
                /*登录成功*/
                return LoginStatusEnum.LOGIN_SUCCESS;
            }
            /*账号或者密码错误*/
            return LoginStatusEnum.USER_OR_PASSWORD_ERROR;
        }
        /*没有该用户*/
        return LoginStatusEnum.NOT_USER;
    }

    /**
     * 用于清除登录用户数据信息
     *
     * @param session  用于清除用户信息
     * @param request  请求参数
     * @param response 响应参数
     */
    @SneakyThrows
    @Override
    public void logoutUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        /*获取所有cookie*/
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                /*取出session域之中存储的user，并且将其删除*/
                String key = URLDecoder.decode(cookie.getName(), "UTF-8");
                User sessionUser = (User) session.getAttribute(key);
                if (sessionUser != null) {
                    session.removeAttribute(key);
                }
                /*将所有cookie删除*/
                Cookie tempCookie = new Cookie(cookie.getName(), cookie.getValue());
                tempCookie.setPath("/BaiGuang");
                tempCookie.setMaxAge(0);
                response.addCookie(tempCookie);
            }
        }
    }

    /**
     * 新增用户功能
     *
     * @param user 新增用户信息封装对象
     * @return
     */
    @Override
    public boolean addNewUser(User user) {
        return this.userMapper.addNewUser(user);
    }

    /**
     * 查询用户信息
     *
     * @param session session域对象
     * @param request 请求参数对象
     * @return User 查询结果
     */
    @SneakyThrows
    @Override
    public User selectUserMessagesById(HttpSession session, @NotNull HttpServletRequest request) {
        /*获取所有cookie*/
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String key = cookie.getName();
                User user = (User) session.getAttribute(key);
                /*查询成功*/
                if (user != null) {
                    return this.userMapper.selectUserMessagesById(user.getUserId());
                }
            }
        }
        /*查询失败*/
        return null;
    }

    /**
     * 查找所有用户信息
     *
     * @return 所有用户信息封装
     */
    @Override
    public List<User> findUserAll() {
        return this.userMapper.findUserAll();
    }

    /**
     * 查询所有用户信息（root）（分页查询）
     *
     * @param paging 查询要求封装
     * @return 查询得到的所有用户结果封装
     */
    @Override
    public List<User> findUserAllLimit(Paging paging) {
        /*先获得表中结果数量*/
        Integer allUserNumber = this.userMapper.findAllUserNumber();
        /*再计算需要把一张表分成多少页*/
        Integer pageNumber = allUserNumber / paging.getEventPageNumber();
        if (pageNumber < paging.getStartPage()) {
            return null;
        }
        paging.setCountPage(allUserNumber);
        paging.setStartPage((paging.getStartPage() - 1) * paging.getEventPageNumber());
        List<User> userList = this.userMapper.findUserAllByLimit(paging);
        return userList;
    }
}
